package keye.document_manage.aop;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import keye.document_manage.dao.sqlserver.BaseDaoSqlserver;
import keye.document_manage.domain.ClassEntityRelation;
import keye.document_manage.entity.SelectParameters;
import keye.document_manage.gui.CheckNode;
import keye.document_manage.service.impl.PushServiceImpl;
import keye.document_manage.util.ConvertStringUtil;
import keye.document_manage.util.MySqlProvider;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Order(2)
public class PushDataAspectAdvice {

	@Resource()
	private BaseDaoSqlserver<?> baseSqlserver;
	
	/**
	 * 用于生成说明文件
	 * @param jp
	 * @return
	 * @throws Throwable
	 */
	@Around("execution(* keye.document_manage.service.*.*.pushDatas(..))")
	public Object doAround4(ProceedingJoinPoint jp)throws Throwable{
		long startTime=System.currentTimeMillis();   //获取开始时间
		Date date = new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		
		Object result = jp.proceed();
		if(result.equals(false))
			return result;
		
		Object[] ob = jp.getArgs();
		jp.getTarget().getClass().getMethods();
		StringBuilder sb = new StringBuilder();
		StringBuilder paras = new StringBuilder();
		StringBuilder category = new StringBuilder();
		Path fpath = null;
		String tableName =null;
		boolean isCopyFile = false;
		for (int i = 0; i < ob.length; i++) {
			if(ob[i] instanceof List){
				sb.append("发布条件：");
				((List<?>)ob[i]).forEach(v->{
					String tm = MySqlProvider.solveParameters((SelectParameters) v);
					paras.append( "and "+tm);
					sb.append(tm+"; ");
				});
			}else if(ob[i] instanceof CheckNode){
				
				CheckNode node = (CheckNode)ob[i];
				ClassEntityRelation cer = (ClassEntityRelation)node.getUserObject();
				if (cer.geteTableName() == null || "".equals(cer.geteTableName()))
					return false;
				node = (CheckNode) node.getFirstLeaf();
				tableName = cer.geteTableName();
				category.append("档案门类："+node.toString()+System.getProperty("line.separator"));
			}if(ob[i] instanceof Boolean){
				isCopyFile = (boolean) ob[i];
			}if(ob[i] instanceof String && i==ob.length-1){
				fpath = Paths.get((String) ob[i]+File.separator+"readme.txt");
				Path p = Paths.get((String) ob[i]+File.separator);
				if(!Files.exists(p)){
					Files.createDirectories(p);
				}
				Files.createFile(fpath);
			}
		}
			
		String selectSQL=null;
		List<HashMap<String, Object>> rs= null;
		if(tableName!= null){
			selectSQL ="SELECT fonds_no FROM "+tableName+" WHERE 1=1 "+paras.toString()+" GROUP BY fonds_no";
			rs = baseSqlserver.executeSelecetSQL(selectSQL);
			category.append("全宗号：");
			rs.forEach(m->category.append(m.get("fonds_no")+" "));
			category.append(System.getProperty("line.separator"));
		}
		
		CheckNode node = (CheckNode)ob[2];
		ClassEntityRelation cer = (ClassEntityRelation) node.getUserObject();
		boolean fog = true;
		int filesCount=0;
		if(node.isLeaf()){
			cer = (ClassEntityRelation) ((CheckNode) node.getParent()).getUserObject();
			if (cer.geteTableName() == null || "".equals(cer.geteTableName())) {
				// 单层结构
				fog = false;
				sb.append(System.getProperty("line.separator")+node+"：");
				selectSQL = "SELECT count(*) as length FROM "+ tableName+" WHERE 1=1 "+paras.toString();
				rs = baseSqlserver.executeSelecetSQL(selectSQL);
				rs.forEach(m->sb.append(m.get("length")+" 条"));
				if(isCopyFile){
					selectSQL = "SELECT count(*) as length FROM is_files as t0, ( SELECT recid FROM "+ tableName+" WHERE 1=1 "+paras.toString()+") as t1 where t0.rec_id=t1.recid";
					rs = baseSqlserver.executeSelecetSQL(selectSQL);
					filesCount = (int) rs.get(0).get("length");
				}
			} else {
				cer = (ClassEntityRelation) node.getUserObject();
			}
		}
		if(fog){
			node = (CheckNode) node.getFirstLeaf();
			cer = (ClassEntityRelation) node.getUserObject();
//			List<String> tables = new ArrayList<String>(5);
			while(cer.geteTableName() != null && !"".equals(cer.geteTableName())) {
				sb.append(System.getProperty("line.separator")+cer.getItemName()+"：");
				if(cer.geteTableName().equals(tableName)){
					selectSQL = "SELECT count(*) as length FROM "+ tableName+" WHERE 1=1 "+paras.toString();
				}else{
					selectSQL = "SELECT count(*) as length FROM "+ cer.geteTableName()+" as t2, "
							+ " (SELECT t.folder_no FROM "+ tableName+" as t WHERE 1=1 "+paras.toString()+") as t1" 
							+ " WHERE t1.folder_no = t2.folder_no";
				}
				rs = baseSqlserver.executeSelecetSQL(selectSQL);
				rs.forEach(m->sb.append(m.get("length")+" 条"));
				node = (CheckNode) node.getParent();
				cer = (ClassEntityRelation) node.getUserObject();
			}
		}
		
		if(fog){
			node = (CheckNode) node.getFirstLeaf();
			cer = (ClassEntityRelation) node.getUserObject();
			//选择的表是和原文有关系的表
			if(cer.geteTableName().equals(tableName)){
				selectSQL = "SELECT count(*) as length FROM is_files as t1 ,(SELECT recid FROM "+ tableName+" WHERE 1=1 "+paras.toString()+") as t2 WHERE t1.rec_id=t2.recid AND t1.tble_name='"+tableName+"' ";
			}else{
				selectSQL = " SELECT count(*) as length FROM is_files as t1 ,"
						+ " (SELECT t.recid FROM "+cer.geteTableName()+" as t,"
						+ " (SELECT folder_no FROM "+ tableName+" WHERE 1=1 "+paras.toString()+") as t3 "
								+ "WHERE t3.folder_no = t.folder_no) as t2 "
								+ "WHERE t1.rec_id=t2.recid AND t1.tble_name='"+tableName+"' ";
			}
			rs = baseSqlserver.executeSelecetSQL(selectSQL);
			filesCount = (int) rs.get(0).get("length");
		}
		
		long endTime=System.currentTimeMillis(); //获取结束时间
		Files.write(fpath, ("发布时间："+sdf.format(date)+System.getProperty("line.separator")+category+sb.toString().replaceAll(" ", "")+System.getProperty("line.separator")).getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
		if(isCopyFile){
			@SuppressWarnings({ "rawtypes", "unchecked" })
			double size = ((PushServiceImpl)jp.getTarget()).calculateSize((List)ob[1], (CheckNode)ob[2]);
			Files.write(fpath, ("原文统计：共 "+filesCount+"条 "+ConvertStringUtil.convertFileSize(size*1024)+System.getProperty("line.separator")).getBytes(), StandardOpenOption.APPEND);
		}
		Files.write(fpath, (System.getProperty("line.separator")+"总耗时： "+ConvertStringUtil.convertTime(endTime-startTime)).getBytes(), StandardOpenOption.APPEND);
		return result;
	}

	public BaseDaoSqlserver<?> getBaseSqlserver() {
		return baseSqlserver;
	}

	public void setBaseSqlserver(BaseDaoSqlserver<?> baseSqlserver) {
		this.baseSqlserver = baseSqlserver;
	} 
}
